package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * 2134. 最少交换次数来组合所有的 1 II
 *
 * @author liw
 * @version 1.0
 * @date 2022/5/6 17:01
 */
public class MinSwaps2134 {

    public static void main(String[] args) {
        MinSwaps2134 test = new MinSwaps2134();

        // 1
//        int[] arr = {0,1,0,1,1,0,0};

        // 2
//        int[] arr = {0,1,1,1,0,0,1,1,0};

        // 0
        int[] arr = {1, 1, 0, 0, 1};
        int i = test.minSwaps(arr);
        System.out.println(i);
    }

    public int minSwaps(int[] nums) {
        int count = 0;
        int length = nums.length;
        for (int num : nums) {
            if (num == 1) {
                count++;
            }
        }
        int item = 0;
        for (int i = 0; i < count; i++) {
            if (nums[i] == 1) {
                item++;
            }
        }
        int a = item;
        int min = count - item;
        for (int i = count; i < length; i++) {
            if (nums[i] == 1) {
                item++;
            }
            if (nums[i - count] == 1) {
                item--;
            }
            min = Math.min(min, count - item);
        }
        item = count - a;
        for (int i = count - 1; i >= 0; i--) {
            if (nums[i] == 1) {
                item++;
            }
            if (nums[i + length - count] == 1) {
                item--;
            }
            min = Math.min(min, item);
        }
        return min;
    }
}
